﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using insidedotnet.UI;

public partial class AdminEditarAnunciante : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = AcheiCampinasConfiguration.SiteName +
            " : editar anúncio de empresa.";

        // check if we must display order details
        if (!Page.IsPostBack)
        {
            string empresaId= Request.QueryString["EmpresaID"];
            // fill constituent controls with data
            PopulateControls(empresaId);
            // set edit mode
            SetEditMode(false);
        }
    }

    private void PopulateControls(string empresaId)
    {
        // obtain order info
        DetalhesEmpresa empresaInfo = CatalogAccess.GetDetalhesEmpresa(empresaId);
        // populate labels and text boxes with order info
        nomeEmpresa.Text = empresaInfo.Nome;
        descricaoEmpresa.Text = empresaInfo.Descricao;
  
        endereco.Text = empresaInfo.Endereco;
        numero.Text = empresaInfo.Numero;
        cep.Text = empresaInfo.Cep;
        telefone.Text = empresaInfo.Telefone;
        celular.Text = empresaInfo.Celular;
        email.Text = empresaInfo.Email;
        paginaweb.Text = empresaInfo.Paginaweb;
        msn.Text = empresaInfo.Msn;
        blog.Text = empresaInfo.Blog;
        youtube.Text = empresaInfo.Youtube;
        twitter.Text = empresaInfo.Twitter;
        facebook.Text = empresaInfo.Facebook;
        orkut.Text = empresaInfo.Orkut;
        imagemLogotipo.ImageUrl = "/ImagensLogos/" + empresaInfo.Logotipo;
        
        // Fill categoriesLabel and categoriesListRemove with data
        string categoryId, categoryName, bairroName, bairroId;
        DataTable productCategories = CatalogAccess.GetCategorias();

        categoriesListAssign.Items.Clear();

        for (int i = 0; i < productCategories.Rows.Count; i++)
        {
            // obtain category id and name
            categoryId = productCategories.Rows[i]["categoriaID"].ToString();
            categoryName = productCategories.Rows[i]["nome"].ToString();
            // populate the list boxes
            categoriesListAssign.Items.Add(new ListItem(categoryName, categoryId));
        }
        categoriesListAssign.SelectedIndex = int.Parse(empresaInfo.CategoriaID) - 1;

        

        DataTable bairros = CatalogAccess.GetBairros();

        bairroList.Items.Clear();
        
        

        for (int i = 0; i < bairros.Rows.Count; i++)
        {
            // obtain category id and name
            bairroId = bairros.Rows[i]["bairroID"].ToString();
            bairroName = bairros.Rows[i]["nome"].ToString();
            // populate the list boxes
            bairroList.Items.Add(new ListItem(bairroName, bairroId));
        }
        bairroList.SelectedIndex = empresaInfo.BairroID - 1;

        // by default the Edit button is enabled, and the
        // Update and Cancel buttons are disabled
        editButton.Enabled = true;
        updateButton.Enabled = false;
        cancelButton.Enabled = false;

    }

    // enable or disable edit mode
    private void SetEditMode(bool enable)
    {

        nomeEmpresa.Enabled = enable;
        descricaoEmpresa.Enabled = enable;
        //categoriesListAssign.SelectedItem.Value = empresaInfo.CategoriaID;

        endereco.Enabled = enable;
        numero.Enabled = enable;
        bairroList.Enabled = enable;
        cep.Enabled = enable;
        telefone.Enabled = enable;
        celular.Enabled = enable;
        email.Enabled = enable;
        paginaweb.Enabled = enable;
        msn.Enabled = enable;
        blog.Enabled = enable;
        youtube.Enabled = enable;
        twitter.Enabled = enable;
        facebook.Enabled = enable;
        orkut.Enabled = enable;
        categoriesListAssign.Enabled = enable;
        image1FileUpload.Enabled = enable;

        editButton.Enabled = !enable;
        updateButton.Enabled = enable;
        cancelButton.Enabled = enable;
    }

    protected void editButton_Click(object sender, EventArgs e)
    {
        string empresaId = Request.QueryString["EmpresaID"];
        PopulateControls(empresaId);
        SetEditMode(true);
    }

    // cancel edit mode
    protected void cancelButton_Click(object sender, EventArgs e)
    {
        string empresaId = Request.QueryString["EmpresaID"];
        SetEditMode(false);
        PopulateControls(empresaId);
    }


    protected void updateButton_Click(object sender, EventArgs e)
    {
        // Store the new order details in an OrderInfo object
        DetalhesEmpresa empresaInfo = new DetalhesEmpresa();
        string empresaId = Request.QueryString["EmpresaID"];

        empresaInfo.EmpresaID = int.Parse(empresaId);
        empresaInfo.Nome = nomeEmpresa.Text;
        empresaInfo.Descricao = descricaoEmpresa.Text;
        empresaInfo.Endereco = endereco.Text;
        empresaInfo.Numero = numero.Text;
        empresaInfo.Cep = cep.Text;
        empresaInfo.Telefone = telefone.Text;
        empresaInfo.Celular = celular.Text;
        empresaInfo.Email = email.Text;
        empresaInfo.Bairro = bairroList.SelectedItem.Text;
        empresaInfo.BairroID = int.Parse(bairroList.SelectedItem.Value);
        empresaInfo.CategoriaID = categoriesListAssign.SelectedValue;

        empresaInfo.Paginaweb = paginaweb.Text;
        empresaInfo.Msn = msn.Text;
        empresaInfo.Blog = blog.Text;
        empresaInfo.Youtube = youtube.Text;
        empresaInfo.Twitter = twitter.Text;
        empresaInfo.Facebook = facebook.Text;
        empresaInfo.Orkut = orkut.Text;

        DateTime agora = DateTime.Now;

        // proceed with uploading only if the user selected a file
        if (image1FileUpload.HasFile)
        {
            try
            {
                string fileName = agora.ToString("dd_MM_yyyy_HH_mm_ss_") + image1FileUpload.FileName;
                string location = Server.MapPath("./ImagensLogos/") + fileName;
                // save image to server
                image1FileUpload.SaveAs(location);

                //create its thumbnail
                Thumbnail.Create(Server.MapPath(""), "ImagensLogos", "ImagensLogos", fileName, 240, 230);

                //delete the original new image. The uploaded one.
                File.Delete(location);


                //delete the old image that was in the server
                DataTable dt = CatalogAccess.GetFileNameLogotipo(empresaId);
                DataRow dr = dt.Rows[0];
                deleteFile(dr["logotipo"].ToString());

                CatalogAccess.UpdateImagemAnunciante(empresaId, "tb_"+fileName);
            }
            catch(System.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }

        // try to update the order
        try
        {
            // Update the order
            CatalogAccess.UpdateAnunciante(empresaInfo);
        }
        catch
        {
            // In case of an error, we simply ignore it
        }
        // Exit edit mode
        SetEditMode(false);
        // Update the form
        PopulateControls(empresaId);
    }
    protected void deleteButton_Click(object sender, EventArgs e)
    {

        string empresaId = Request.QueryString["EmpresaID"];
        // Delete the product from the catalog
        
        DataTable dt = CatalogAccess.GetFileNameLogotipo(empresaId);
        DataRow dr = dt.Rows[0];

        CatalogAccess.DeleteEmpresa(empresaId);

        deleteFile(dr["logotipo"].ToString());

        
        // Need to go back to the categories page now
        Response.Redirect("Mensagens.aspx?n=3");
    }

    protected void deleteFile(String filename)
    {
        // Delete a file by using File class static method...
        if (System.IO.File.Exists(Server.MapPath("./ImagensLogos/") + filename))
        {
            // Use a try block to catch IOExceptions, to
            // handle the case of the file already being
            // opened by another process.
            try
            {
                System.IO.File.Delete(Server.MapPath("./ImagensLogos/") + filename);
            }
            catch (System.IO.IOException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }
    }
}